rm(list= ls())

library(tidyverse)
library(lfe)

## Load Election Data

dat <- readRDS('data/fed_elections_kreise.rds') %>%
  filter(year >= 1961) %>% 
  filter(year <= 1965) %>%
  filter(type == 'Stadtkreis') 

## Define outcomes 

outcomevars <- c('fdp',
                 'far_right_vs_excl_dp',
                 'spd')

## Leave states out one by one 

res_all <- lapply(unique(dat$state_id), function(state_id_out){
  
  pre_year <- 1961
  post_year <- 1965 
  
  lapply(outcomevars, function(dv){
    
    ## Define treated * post variable 
    
    dat_new <- dat %>% 
      filter(year %in% c(post_year, pre_year)) %>% 
      mutate(post = ifelse(year >= post_year, 1, 0)) %>%
      mutate(treated_post = n_syn_bin * post) %>%
      mutate(treated = n_syn_bin) %>%
      mutate(year = as.character(year)) %>%
      filter(!state_id %in% state_id_out)
    
    m1 <- as.formula(paste(dv, 'treated_post | county_id_1950 + year | 0 | county_id_1950', sep = '~'))
    
    mlist <- list(m1)
    
    
    tryCatch({
      
      results <- felm(m1, data = dat_new) %>%
        broom::tidy(conf.int = T) %>%
        filter(term == 'treated_post') %>%
        mutate(model_formula = deparse(m1)[1]) %>%
        mutate(outcome = dv,
               state_out = state_id_out,
               post_year = post_year,
               time_period = paste(pre_year, post_year, sep = ' - ')) }, 
      
      error = function(e){cat("ERROR :",conditionMessage(e), "\n")}) 
    
  }) %>% reduce(rbind)
}) %>% reduce(rbind) %>%
  arrange(outcome)

## Add labels for outcomes

res_all <- res_all %>%
  mutate(outcome_label = recode(outcome,
                                `far_right_vs_excl_dp` = 'Far right\n(NPD/DRP)',
                                `spd` = 'SPD',
                                `fdp` = 'FDP')) %>%
  dplyr::select(-one_of('f_stat', 'f_pval', 'a_rsq'))

## Recode state IDs 

res_all <- res_all %>%
  mutate(state_label = recode(state_out,
                              `01` = 'Schleswig-Holstein',
                              `02` = 'Hamburg',
                              `03` = 'Lower Saxony',
                              `04` = 'Bremen',
                              `05` = 'Nordrhein-Westfalen',
                              `06` = 'Hessen',
                              `07` = 'Rheinland-Pfalz.',
                              `08` = 'Baden-Württemberg',
                              `09` = 'Bayern'))

## Plot This 

p1 <- ggplot(res_all, aes(x = state_label, y = estimate, ymin = conf.low, ymax = conf.high)) + 
  geom_errorbar(width = 0) + 
  geom_point(shape = 21, fill = 'white') + 
  theme_classic() + 
  facet_grid(~ outcome_label) + 
  geom_hline(yintercept = 0, linetype = 'dotted') +
  labs(x = 'State left out',
       y = 'DiD Effect estimate') + 
  haschaR::x_axis_90deg()


p1 


